#include <mprpcconfig.h>
#include <iostream>
#include <string>
#include <logger.h>

void MprpcConfig::LoadConfigFile(const char *config_file)
{
    FILE *pf = fopen(config_file, "r");
    if (pf == nullptr)
    {
        LOG_ERROR("%s : config file is not exist!", config_file);
        // std::cout << "config file is not exist!" << std::endl;
        exit(EXIT_FAILURE);
    }
    while (!feof(pf))
    {
        char buf[512] = {0};
        fgets(buf, 512, pf);

        std::string src_buf(buf);
        Trim(src_buf);
        if (src_buf[0] == '#' || src_buf.empty())
        {
            continue;
        }
        int eqIndex = src_buf.find('=');
        if (eqIndex == -1)
        {
            continue;
        }
        std::string key = src_buf.substr(0, eqIndex);
        int endIndex = src_buf.find('\n'); // 一定会有这个\n，所以不需要判断
        std::string value = src_buf.substr(eqIndex + 1, endIndex - eqIndex - 1);
        Trim(key);
        Trim(value);
        m_configMap[key] = value;
    }
}

void MprpcConfig::Trim(std::string &srcStr)
{
    int leftIndex = srcStr.find_first_not_of(' ');
    if (leftIndex != -1)
    {
        srcStr = srcStr.substr(leftIndex, srcStr.size() - leftIndex);
    }
    int rightIndex = srcStr.find_last_not_of(' ');
    if (rightIndex != -1)
    {
        srcStr = srcStr.substr(0, rightIndex + 1);
    }
}
std::string MprpcConfig::Load(const std::string &key)
{
    if (m_configMap.find(key) != m_configMap.end())
    {
        return m_configMap[key];
    }
    return "";
}